package model

import(
	"fmt"
	"github.com/garyburd/redigo/redis"
	"encoding/json"
	"project06/common/message"
)

var(
	MyUserDao *UserDao
)

type UserDao struct{
	pool *redis.Pool
}

func NewUserDao(pool *redis.Pool) (userDao *UserDao){
	userDao = &UserDao{
		pool:pool,
	}
	return
}

func (this *UserDao) getUserById(conn redis.Conn,userId int) (user *User,err error){
	mes,err:=redis.String(conn.Do("hget","users",userId))
	if err !=nil{
		if err == redis.ErrNil{
			err= ERR_USER_NOEXISTS
		}
		return
	}
	user =&User{}
	//fmt.Println("json.Unmarshal before mes ",mes)
	err = json.Unmarshal([]byte(mes),&user)
	if err!=nil{
		fmt.Println("json.Unmarshal err ",err)
		return
	}
	return
}

func (this *UserDao) Login(userId int,userPwd string) (user *User,err error){
	conn:=this.pool.Get()
	defer conn.Close()
	user,err=this.getUserById(conn,userId)
	if err!=nil{
		return
	}
	if user.UserPwd!=userPwd{
		err =ERR_USER_PWD
		return
	}
	return
}

func (this *UserDao) Register(user *message.User) (err error){
	conn:=this.pool.Get()
	defer conn.Close()
	_,err=this.getUserById(conn,user.UserId)
	if err==nil{
		err =ERR_USER_EXISTS
		return
	}
	data,err:=json.Marshal(user)
	if err!=nil{
		fmt.Println("序列化失败")
		return
	}
	_,err=conn.Do("hset","users",user.UserId,string(data))
	if err!=nil{
		fmt.Println("保存注册用户失败")
		return
	}
	return
}